package com.csot.ry.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.csot.ry.domain.TCitySegment;
import com.csot.ry.domain.TTotalSegment;
import com.csot.ry.poi.ExcelUtilSub;
import com.csot.ry.service.ITCitySegmentService;
import com.csot.ry.util.CacheKitUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.csot.common.annotation.Log;
import com.csot.common.constant.HttpStatus;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.core.page.TableDataInfo;
import com.csot.common.enums.BusinessType;
import com.csot.common.utils.ServletUtils;
import com.csot.common.utils.StringUtils;
import com.csot.common.utils.poi.ExcelUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 城市ip段Controller
 * 
 * @author 刘沙
 * @date 2022-05-31
 */
@RestController
@RequestMapping("/ipmanagement/citysegment")
public class TCitySegmentController extends BaseController {

	@Autowired
	private ITCitySegmentService tCitySegmentService;

	/**
	 * 查询城市ip段列表
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:list')")
	@GetMapping("/list/{type}")
	public TableDataInfo list(TCitySegment tCitySegment,@PathVariable("type") String type) {
		try {
			startPage();
			tCitySegment.setIpType(type.toLowerCase());
			List<TCitySegment> list = tCitySegmentService.selectTCitySegmentList(tCitySegment);
			return super.getDataTable(list);
		} catch (Exception e) {
			TableDataInfo rspData = new TableDataInfo();
			rspData.setCode(HttpStatus.ERROR);
			rspData.setMsg(StringUtils.isNotEmpty(e.getMessage()) ? "请联系管理员：" + e.getMessage() : "查询失败，请联系管理员");
			rspData.setRows(null);
			rspData.setTotal(0);
			return rspData;
		}
	}

	@Log(title = "城市ip段导入查询", businessType = BusinessType.IMPORT)
	@PostMapping("/importQuery/{type}")
	public TableDataInfo importQuery(MultipartFile file, boolean updateSupport,@PathVariable("type") String type) throws Exception {
		try {
			HttpSession hs = ServletUtils.getSession();
			startPage();
			ExcelUtilSub<TCitySegment> util = new ExcelUtilSub<TCitySegment>(TCitySegment.class);
			List<TCitySegment> tCitySegmentList = util.importExcel(file.getInputStream());
			for(TCitySegment tCitySegment : tCitySegmentList){
				tCitySegment.setIpType(type.toLowerCase());
			}
			List<TCitySegment> list = tCitySegmentService.selectTCitySegmentLists(tCitySegmentList);
			hs.setAttribute("ipmanagement:citysegment:importQuery", list);
			return super.getDataTable(list);
		} catch (Exception e) {
			TableDataInfo rspData = new TableDataInfo();
			rspData.setCode(HttpStatus.ERROR);
			rspData.setMsg("查询失败");
			rspData.setRows(null);
			rspData.setTotal(0);
			return rspData;
		}
	}

	/**
	 * 导出城市ip段列表
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:exportQuery')")
	@Log(title = "城市ip段导出查询", businessType = BusinessType.EXPORT)
	@PostMapping("/exportQuery")
	public void exportQuery(HttpServletResponse response) {
		List<TCitySegment> result = new ArrayList<>();
		HttpSession hs = ServletUtils.getSession();
		Object obj = hs.getAttribute("ipmanagement:citysegment:importQuery");
		if (Objects.nonNull(obj)) {
			if (obj instanceof List) {
				result = (List) obj;
			}
		}
		for (TCitySegment t : result) {
			t.setIpType(CacheKitUtil.ip_type.get(t.getIpType()));
			t.setIpCity(CacheKitUtil.ip_city.get(t.getIpCity()));
			t.setRecordStatus(CacheKitUtil.ip_record.get(t.getRecordStatus()));
			t.setIpStatus(CacheKitUtil.ip_status.get(t.getIpStatus()));
			t.setIpUseType(CacheKitUtil.ip_use_type.get(t.getIpUseType()));
		}
		ExcelUtilSub<TCitySegment> util = new ExcelUtilSub<TCitySegment>(TCitySegment.class);
		util.exportExcel(response, result, "地市ip段查询数据");

	}

	/**
	 * 导出城市ip段列表
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:export')")
	@Log(title = "城市ip段", businessType = BusinessType.EXPORT)
	@PostMapping("/export/{type}")
	public void export(HttpServletResponse response, TCitySegment tCitySegment,@PathVariable("type") String type) {
		String parentId = getLoginUser().getUser().getDept().getParentId() + "";
		if (CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId) && !"0".equals(parentId)) {
			tCitySegment.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
		}
		tCitySegment.setIpType(type.toLowerCase());
		List<TCitySegment> list = tCitySegmentService.selectTCitySegmentList(tCitySegment);
		for (TCitySegment t : list) {
			t.setIpType(CacheKitUtil.ip_type.get(t.getIpType()));
			t.setIpCity(CacheKitUtil.ip_city.get(t.getIpCity()));
			t.setRecordStatus(CacheKitUtil.ip_record.get(t.getRecordStatus()));
			t.setIpStatus(CacheKitUtil.ip_status.get(t.getIpStatus()));
			t.setIpUseType(CacheKitUtil.ip_use_type.get(t.getIpUseType()));
		}
		ExcelUtil<TCitySegment> util = new ExcelUtil<TCitySegment>(TCitySegment.class);
		util.exportExcel(response, list, "互联网细粒度IP");
	}

	@Log(title = "城市ip段导入", businessType = BusinessType.IMPORT)
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:import')")
	@PostMapping("/importData/{type}")
	public AjaxResult importData(MultipartFile file, boolean updateSupport,@PathVariable("type") String type) throws Exception {
		ExcelUtilSub<TCitySegment> util = new ExcelUtilSub<TCitySegment>(TCitySegment.class);
		List<TCitySegment> tCitySegmentList = util.importExcel(file.getInputStream());
		for(TCitySegment tCitySegment : tCitySegmentList){
			tCitySegment.setIpType(type.toLowerCase());
		}
		return toAjax(tCitySegmentService.importCitySegment(tCitySegmentList));
	}
	@Log(title = "城市ip段导入修改", businessType = BusinessType.IMPORT)
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:import')")
	@PostMapping("/importDataEdit/{type}")
	public AjaxResult importDataEdit(MultipartFile file, boolean updateSupport,@PathVariable("type") String type) throws Exception {
		ExcelUtilSub<TCitySegment> util = new ExcelUtilSub<TCitySegment>(TCitySegment.class);
		List<TCitySegment> tCitySegmentList = util.importExcel(file.getInputStream());
		for(TCitySegment tCitySegment : tCitySegmentList){
			tCitySegment.setIpType(type.toLowerCase());
		}
		return toAjax(tCitySegmentService.importCitySegmentEdit(tCitySegmentList));
	}

	@PostMapping("/importTemplate")
	public void importTemplate(HttpServletResponse response) {
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		try {
			String path = System.getProperty("user.dir");
			path = path + File.separator + "Template" + File.separator + "citysegmentmodel.xlsx";
			IOUtils.write(Files.readAllBytes(Paths.get(path)), response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("下载ip段模块异常", e);
		}
	}

	@PostMapping("/importTemplateq")
	public void importTemplateq(HttpServletResponse response) {
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		try {
			String path = System.getProperty("user.dir");
			path = path + File.separator + "Template" + File.separator + "citysegmentmodel.xlsx";
			IOUtils.write(Files.readAllBytes(Paths.get(path)), response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("下载ip段模块异常", e);
		}
	}

	/**
	 * 获取城市ip段详细信息
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(tCitySegmentService.selectTCitySegmentById(id));
	}

	/**
	 * 新增城市ip段
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:add')")
	@Log(title = "城市ip段", businessType = BusinessType.INSERT)
	@PostMapping(value = "/{type}")
	public AjaxResult add(@RequestBody TCitySegment tCitySegment,@PathVariable("type") String type) {
		tCitySegment.setIpType(type.toLowerCase());
		return toAjax(tCitySegmentService.insertTCitySegment(tCitySegment));
	}

	/**
	 * 修改城市ip段
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:edit')")
	@Log(title = "城市ip段", businessType = BusinessType.UPDATE)
	@PutMapping(value = "/{type}")
	public AjaxResult edit(@RequestBody TCitySegment tCitySegment,@PathVariable("type") String type) {
		tCitySegment.setIpType(type.toLowerCase());
		return toAjax(tCitySegmentService.updateTCitySegment(tCitySegment));
	}

	/**
	 * 删除城市ip段
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:citysegment:remove')")
	@Log(title = "城市ip段", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(tCitySegmentService.deleteTCitySegmentByIds(ids));
	}

	@Override
	protected TableDataInfo getDataTable(List<?> list) {
		PageUtil.setFirstPageNo(1);
		TableDataInfo rspData = new TableDataInfo();
		rspData.setCode(HttpStatus.SUCCESS);
		rspData.setMsg("查询成功");
		Page<Object> page = PageHelper.getLocalPage();
		int[] ps = PageUtil.transToStartEnd(page.getPageNum(), page.getPageSize());
		if (CollUtil.isEmpty(list)) {
			rspData.setRows(list);
			rspData.setTotal(new PageInfo(new ArrayList<>()).getTotal());
		} else {
			rspData.setRows(CollUtil.sub(list, ps[0], ps[1]));
			rspData.setTotal(list.size());
		}

		return rspData;
	}
}
